package com.demo.webapp.views.freemarker.directive.core;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.views.freemarker.FreemarkerManager;

import com.demo.common.StringUtils;

import freemarker.core.Environment;
import freemarker.core.Environment.TemplateDirectiveBodyEx;
import freemarker.ext.servlet.HttpRequestHashModel;
import freemarker.template.SimpleHash;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;

/**
 * 自定义指令: 分页
 * 该分页自定义指令需要满足对象
 * @author ryuu.kk
 *
 */
public class UrlDirective extends BaseDirectiveSupport {

	/**
	 * 页面模板名
	 */
	private static final String URL_PATH = "classpath:/com/demo/webapp/views/freemarker/directive/template/url.ftl";
	
	@SuppressWarnings("rawtypes")
	@Override
	public void preWriter(Environment env, TemplateDirectiveBodyEx bodyEx,
			TemplateModel[] loopVars, SimpleHash hash, Map params)
			throws IOException, TemplateException {
		
		String value = "";
		String url = "";
		String query = "";
		HttpServletRequest request = null;;
		HttpServletResponse response = null;
		
		try {
			HttpRequestHashModel requestModel = (HttpRequestHashModel) hash.get(FreemarkerManager.KEY_REQUEST);
			if (requestModel == null) {
				throw new TemplateException("HttpRequestHashModel is null.", env);
			}
			request = requestModel.getRequest();
			value = getString("value", params, "/");
			query = getString("params", params);
			response = requestModel.getResponse();
			if (query != null) {
				if (value.indexOf("?") > 0) {
					value += "&" + query;
				} else {
					value += "?" + query;
				}
			}
			if (value.startsWith("/")) {
				value = request.getContextPath() + value;
			}
			url = response.encodeURL(value);
		} catch (TemplateModelException e) {
			e.printStackTrace();
		}
		//hash.put("page", page);
		hash.put("url", url);
	}
	
	@SuppressWarnings("rawtypes")
	@Override
	public String getTemplatePath(Map params) {
		String path = "";
		try {
			path = getString("path", params, URL_PATH);
		} catch (TemplateModelException e) {}
		return path;
	}
	
	@SuppressWarnings("rawtypes")
	@Override
	protected String processSource(String source, SimpleHash hash, Map params) {
		if (StringUtils.isEmpty(source)) {
			source = "${url}";
		} 
		return source;
	}
	
	@Override
	public void afterInvoke(Writer writer) {
		// nothing.
	}
}
